const express = require('express');
const router = express.Router();
const Models = require('./db');
let mongoose = require('mongoose');
const Schema = mongoose;
const { type, role, movie } = Models;

const TypeModel = type
const RoleModel = role;
const VideoModel = movie;

const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER - 1;

/**
 * 焦点轮播图
 * 
 */
router.get('/indexBanner', function (req, res, next) {
  const model = Models.movie;
  model.find({ commend: 1 }, "-_id name preImg", (err, data) => {
    if (err) throw err;
    res.status(200);
    res.json(data);
  }).skip(1).limit(3)
  // model.find({commend:1},{_id:0,name:1,prImg:1},(err,data)=>{
  //   if(err) throw err;
  //   res.status(200);
  //   res.json(data);
  // }).skip(1).limit(3)

});


/**
 * 推荐轮播图
 */
router.post('/getCommendBanner', (req, res) => {
  const model = Models.movie;
  model.find({ commend: 1 }, (err, data) => {
    if (err) throw err;
    res.status(200);
    res.json(data)
  }).limit(6)
})

// 最近更新/今日热门
router.post('/getHotSport', (req, res) => {
  const model = Models.movie;
  model.find({ upId: 1 }, '-_id name preImg auth preVideo des commendInfo', (err, data) => {
    if (err) throw err;
    res.status(200)
    res.json(data)
  }).limit(6)
})


/**
 * 查询接口
 * @params  name 查询词
 * @params  page 当前分页数,默认每5一页
 * @return  data 数据列表
 *          total 总页数
 */
router.get('/video', async (req, res) => {
  let { page, pageSize, name, tagId } = req.query;
  page = Math.floor(page) || 0;
  pageSize = Math.floor(pageSize) || MAX_SAFE_INTEGER;
  tagId = Array.isArray(tagId) ? tagId : !tagId ? [] : [tagId];

  try {
    let query = {};

    if (tagId.length && name) {
      query = {
        $and: [
          {
            tags: {
              $elemMatch: {
                _id: {
                  $in: tagId.map(item => Schema.Types.ObjectId(item))
                }
              }
            },
          },
          {
            $or: [
              {
                roles: {
                  $elemMatch: {
                    name: {
                      $regex: name,
                      $options: 'im'
                    }
                  }
                }
              },
              {
                name: {
                  $regex: name,
                  $options: 'im'
                }
              }
            ]
          }
        ]
      };
    } else if (tagId.length) {
      query = {
        tags: {
          $elemMatch: {
            _id: {
              $in: tagId.map(item => Schema.Types.ObjectId(item))
            }
          }
        },
      };
    } else if (name) {
      // 视频名称或角色名查找
      query.$or = [
        {
          roles: {
            $elemMatch: {
              name: {
                $regex: name,
                $options: 'im'
              }
            }
          }
        },
        {
          name: {
            $regex: name,
            $options: 'im'
          }
        }
      ];
    }

    const count = await VideoModel.count(query);
    const result = await VideoModel.find(query).sort({ updated_at: -1 }).skip(page).limit((page - 1) * pageSize);
    // 遍历role数据查询
    for (let i = 0; i < result.length; i++) {

      const temp = await RoleModel.find({
        _id: {
          $in: result[0].roles
        }
      })
      result[i].roles = temp;
    }
    res.json({ data: result, total: count });
  } catch (err) {
    res.json({ msg: '服务器出错' });
  }
})
  .post('/video', async (req, res) => {
    let { roles, tags, sixList, hallmarks, ...params } = req.body;
    tags = Array.isArray(tags) ? tags : !tags ? [] : String(tags).split(',');
    roles = Array.isArray(roles) ? roles : !roles ? [] : String(roles).split(',');
    sixList = Array.isArray(sixList) ? sixList : !sixList ? [] : String(sixList).split(',');
    hallmarks = Array.isArray(hallmarks) ? hallmarks : !hallmarks ? [] : String(hallmarks).split(',');

    // 检索完整字段
    tags = await TypeModel.find({
      _id: {
        $in: tags.map(item => Schema.Types.ObjectId(item))
      }
    });

    // roles = await RoleModel.find({
    //   _id: {
    //     $in: roles.map(item => Schema.Types.ObjectId(item))
    //   }
    // });
    // roles数据除去id其余为动态的,视频数据存id动态查询

    try {
      const tempResult = await VideoModel.create({
        tags,
        roles,
        sixList,
        hallmarks,
        ...params
      });
      const result = await VideoModel.findById(tempResult._id);
      res.json({ data: result });
    } catch (err) {
      res.json({ msg: '创建失败' });
    }
  })
  .put('/video', async (req, res) => {
    let { id, roles, tags, sixList, hallmarks, ...params } = req.body;
    tags = Array.isArray(tags) ? tags : !tags ? [] : String(tags).split(',');
    roles = Array.isArray(roles) ? roles : !roles ? [] : String(roles).split(',');
    sixList = Array.isArray(sixList) ? sixList : !sixList ? [] : String(sixList).split(',');
    hallmarks = Array.isArray(hallmarks) ? hallmarks : !hallmarks ? [] : String(hallmarks).split(',');

    // 检索完整字段
    tags = await TypeModel.find({
      _id: {
        $in: tags.map(item => Schema.Types.ObjectId(item))
      }
    });

    // roles = await RoleModel.find({
    //   _id: {
    //     $in: roles.map(item => Schema.Types.ObjectId(item))
    //   }
    // });
    // console.log(roles)
    try {
      const tempResult = await VideoModel.findByIdAndUpdate(id, {
        tags,
        roles,
        sixList,
        hallmarks,
        updated_at: Date.now(),
        ...params
      });
      const result = await VideoModel.findById(tempResult._id);
      res.json({ data: result });
    } catch (err) {
      res.json({ msg: '更新失败' });
    }
  })
  .delete('/video/delete', async (req, res) => {
    const idsMap = (req.query.id || '').toString().split(',');

    for (let i = 0; i < idsMap.length; i++) {
      await VideoModel.findByIdAndRemove(idsMap[i]);
    }

    res.json({ msg: 'success' });
  })
  .post('/video/recommend', async (req, res) => {
    const { id, recommend = true } = req.body;
    let commend = recommend ? 1 : 0;
    // fix修正
    try {
      const result = await VideoModel.findByIdAndUpdate(id, { recommend, commend });
      res.json({ data: result });
    } catch (err) {
      res.json({ msg: '更新失败' });
    }
  })
  .get('/video/list', async (req, res) => {
    const tagsList = await TypeModel.find();
    const data = {};
    for (let i = 0; i < tagsList.length; i++) {
      const name = tagsList[i].name;
      const result = await VideoModel.find({
        tags: {
          $elemMatch: {
            name: name
          }
        }
      }).sort({ updated_at: - 1 }).skip(0).limit(6);
      data[name] = result;
    }
    res.json({ data: data });
  })
  .get('/video/find', async (req, res) => {
    let { page, pageSize, tagName, sexName, hallmark, language } = req.query;
    page = Math.floor(page) || 0;
    pageSize = Math.floor(pageSize) || MAX_SAFE_INTEGER;

    const findArray = [];
    let query = {};

    if (language) {
      findArray.push({
        language: language
      });
    }

    if (tagName) {
      findArray.push({
        tags: {
          $elemMatch: {
            name: tagName
          }
        }
      });
    }

    if (sexName) {
      findArray.push({
        sixList: {
          $elemMatch: {
            $eq: sexName
          }
        }
      });
    }

    if (hallmark) {
      findArray.push({
        hallmarks: {
          $elemMatch: {
            $eq: hallmark
          }
        }
      });
    }



    if (findArray.length === 1) {
      query = findArray[0];
    } else {
      query.$and = findArray;
    }

    if (!findArray.length) query = {};

    try {
      const count = await VideoModel.count(query);
      const result = await VideoModel.find(query).sort({ updated_at: -1 }).skip(page).limit((page - 1) * pageSize);
      res.json({ data: result, total: count });
    } catch (err) {
      res.json({ msg: '服务器出错' });
    }
  });




/**
 * 播放地址查询
 * @params _id  查询id
 */
router.post('/getVideoSrc', (req, res) => {
  const model = Models.play;
  // const model=Models.movie;
  //模糊查询参数

  // model.find({_id:req.body._id}).populate('playId').exec((err,data)=>{
  //   if(err) throw err;
  //   console.log('res/'+data.playtId);
  //     res.status(200);
  //     res.json({
  //         data
  //     })
  // })
  model.find({ _id: req.body._id }, (err, data) => {
    if (err) throw err;
    console.log('res/' + data.playtId);
    res.status(200);
    res.send({
      data
    })
  })
});



// 视频分类增删改查
const VIDEO_TAG_API = '/video/tag';
router
  .post(VIDEO_TAG_API, (req, res) => {
    const { name, ...params } = req.body;
    if (!name) {
      res.json({ msg: '参数错误' });
      return;
    }
    TypeModel.create({ name, ...params }, function (err, result) {
      if (err) {
        res.json({ msg: '创建失败' });
      }
      res.json({ data: result });
    })
  })
  .delete(VIDEO_TAG_API, async (req, res) => {
    const idsMap = (req.query.id || '').toString().split(',');

    for (let i = 0; i < idsMap.length; i++) {
      await TypeModel.findByIdAndRemove(idsMap[i]);
    }

    res.json({ msg: 'success' });
  })
  .get(VIDEO_TAG_API, async (req, res) => {
    let { id, page, pageSize } = req.query;
    page = Math.floor(page) || 0;
    pageSize = Math.floor(pageSize) || MAX_SAFE_INTEGER;

    if (id) {
      try {
        const result = await TypeModel.findById(id);
        res.json({ data: result });
      } catch (err) {
        res.json({ msg: '无此记录' })
      }
      return;
    }

    if (Number.isInteger(page) && Number.isInteger(pageSize)) {
      const count = await TypeModel.count();
      const result = await TypeModel.find().sort({ updated_at: - 1 }).skip(page * pageSize).limit((page + 1) * pageSize);
      res.json({
        total: count,
        data: result
      });
      return;
    }

    res.json({ msg: '参数异常' });
  })
  .put(VIDEO_TAG_API, async (req, res) => {
    const { id, ...params } = req.body;
    try {
      const result = await TypeModel.findByIdAndUpdate(id, { updated_at: Date.now(), ...params });
      res.json({ data: result });
    } catch (err) {
      res.json({ msg: '编辑失败' });
    }
  });


//角色库
const ROLE_API = '/role';
const ROLE_POSTER = '/role/poster';
router
  .post(ROLE_API, (req, res) => {
    const { name, des, status, intro, introImgs,nameImgs} = req.body;
    const Model = Models.role;
    if (!name) {
      res.json({ msg: 'name参数错误' });
      return;
    }
    Model.create({ name, des, status, intro, introImgs,nameImgs }, function (err, result) {
      if (err) {
        res.json({ msg: '创建失败' });
      }
      res.json({ data: result });
    })
  })
  .delete(ROLE_API, async (req, res) => {
    const idsMap = (req.query.id || '').toString().split(',');

    for (let i = 0; i < idsMap.length; i++) {
      await RoleModel.findByIdAndRemove(idsMap[i]);
    }

    res.json({ msg: 'success' });
  })
  .get(ROLE_API, async (req, res) => {
    let { id, page, pageSize, name } = req.query;
    page = Math.floor(page) || 0;
    pageSize = Math.floor(pageSize) || MAX_SAFE_INTEGER;
    let query = {};
  
    if (id) {
      try {
        const result = await RoleModel.findByIdAndUpdate(id);
        res.json({ data: result });
      } catch (err) {
        res.json({ msg: '无此记录' })
      }
      return;
    }
  
    if (name) {
      query = {
        name: {
          $regex: name,
          $options: 'im'
        }
      };
    }
  
    if (Number.isInteger(page) && Number.isInteger(pageSize)) {
      const count = await RoleModel.count(query);
      const result = await RoleModel.find(query).sort({ updated_at: - 1 }).skip(page * pageSize).limit((page + 1) * pageSize);
      res.json({
        total: count,
        data: result
      });
      return;
    }
  
    res.json({ msg: '参数异常' });
  })
  .put(ROLE_API, async (req, res) => {
    const { id, ...params } = req.body;

    if (!params.name) {
      res.json({ msg: '姓名不能为空' })
      return;
    }

    try {
      const result = await RoleModel.findByIdAndUpdate(id, { updated_at: Date.now(), ...params });
      res.status(200);
      res.json({ data: result });
    } catch (err) {
      res.json({ msg: '编辑失败' });
    }
  })
  .get(ROLE_POSTER, async (req, res) => {
    const { id, page, pageSize } = req.query;
    if(id&&page&&pageSize){
      let data = await VideoModel.find({ roles:{$in:id}  }).sort({ updated_at: - 1 })
      let total = await VideoModel.countDocuments({ roles:{$in:id}  });
      let tagsArray = [], hallmarkArray = [], sixlIstArray = [], langArray = [];
      for (let i = 0; i < data.length; i++) {
          tagsArray.push(data[i].tags);
          if(data[i].hallmarks.length!==0){
            hallmarkArray.push(data[i].hallmarks.toString());
          }
          sixlIstArray.push(data[i].sixList.toString());
          langArray.push(data[i].language);
      };
      tagsArray = [...new Set(tagsArray)];
      hallmarkArray = [...new Set(hallmarkArray)];
      sixlIstArray = [...new Set(sixlIstArray)];
      langArray = [...new Set(langArray)];
  
      res.json({
          data,
          tagsArray,
          hallmarkArray,
          sixlIstArray,
          langArray
      });
      return;
    }else{
      res.json({ msg: '参数异常' });
    }
    
  
    
  })


module.exports = router;
